const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('node:path')
const { SerialPort } = require('serialport');

function createWindow () {
    const mainWindow = new BrowserWindow({
        width: 1000,
        height: 800,
        autoHideMenuBar: true,
        // alwaysOnTop: true,
        webPreferences: {
            contextIsolation: true,
            sandbox: false,
            preload: path.join(__dirname, 'preload.js')
        }
    })

    ipcMain.on('set-title', (event, title) => {
        const webContents = event.sender
        const win = BrowserWindow.fromWebContents(webContents)
        win.setTitle(title)
    })

    let sp = undefined
    ipcMain.on('SerialPort-list', (event, message) => {
        SerialPort.list().then((ports) => {
            event.returnValue = ports;
        }).catch((err) => {
            console.log(err);
        });
    })
    ipcMain.on('link-SerialPort', (event, message) => {
        console.log(message);
        sp = new SerialPort({path: message, baudRate: 115200, autoOpen: false});
        sp.open();
        event.returnValue = "open ok";
    })
    ipcMain.on('close-SerialPort', (event, message) => {
        sp.close();
        event.returnValue = "close ok";
    })
    ipcMain.on('read-SerialPort', (event, message) => {
        event.returnValue = sp.read()
    })

    mainWindow.loadFile('./src/index.html')

    // mainWindow.webContents.openDevTools()
}

app.whenReady().then(() => {
    createWindow();

    app.on('activate', function () {
        if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
})

app.on('window-all-closed', function () {
    if (process.platform !== 'darwin') app.quit()
})